﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using lumo;
using Microsoft.Xna.Framework;

namespace game.display.effect
{
    public class Blur
    {
        //
        private RenderTarget2D TempTarget;
        private RenderTarget2D FinalTarget;
        private LumoComponent  Component;
        private Effect         BlurEffect;
        private float          Offset;
        //
        public Blur(LumoComponent Component, int W, int H, float Offset = 2.1f)
        {
            this.Component = Component;
            this.Offset = Offset;
            BlurEffect  = Component.Content.Load<Effect>("Effects/Blur");
            TempTarget  = new RenderTarget2D(Component.GraphicsDevice, W, H, false, SurfaceFormat.Color, DepthFormat.None);
            FinalTarget = new RenderTarget2D(Component.GraphicsDevice, W, H, false, SurfaceFormat.Color, DepthFormat.None);
        }

        //
        public Texture2D Apply(Texture2D TexToBeBlurred)
        {
            GraphicsDevice GraphicsDevice = Component.GraphicsDevice;
            SpriteBatch    SpriteBatch = Component.SpriteBatch;

            GraphicsDevice.SetRenderTarget(TempTarget);
            BlurEffect.Parameters["PixelOffset"].SetValue(new Vector2(Offset / TempTarget.Width, 0));
            SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, SamplerState.LinearClamp, DepthStencilState.None, null, BlurEffect);
            SpriteBatch.Draw(TexToBeBlurred, new Rectangle(0, 0, TempTarget.Width, TempTarget.Height), Color.White);
            SpriteBatch.End();

            GraphicsDevice.SetRenderTarget(FinalTarget);
            BlurEffect.Parameters["PixelOffset"].SetValue(new Vector2(0, Offset / TempTarget.Height));
            SpriteBatch.Begin(SpriteSortMode.Immediate, BlendState.Opaque, SamplerState.LinearClamp, DepthStencilState.None, null, BlurEffect);
            SpriteBatch.Draw(TempTarget, Vector2.Zero, Color.White);
            SpriteBatch.End();

            return FinalTarget;
        }
    }
}
